package com.ilop.sthome.ui.activity.detail.thermostat;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import androidx.core.content.ContextCompat;

import com.ilop.sthome.ui.activity.main.ContainLoginActivity;
import com.example.common.utils.LiveDataBus;
import com.example.common.utils.SpUtil;
import com.example.common.view.dialog.SetLoadingDialog;
import com.ilop.sthome.common.CommonId;
import com.ilop.sthome.common.command.SiterCommand;
import com.ilop.sthome.data.event.EventAnswerOK;
import com.ilop.sthome.data.event.EventRefreshDevice;
import com.ilop.sthome.data.greenDao.DeviceInfoBean;
import com.ilop.sthome.mvp.contract.device.ThermostatContract;
import com.ilop.sthome.mvp.present.device.ThermostatPresenter;
import com.ilop.sthome.ui.activity.detail.socket.TimingListActivity;
import com.ilop.sthome.ui.activity.device.DeviceDetailActivity;
import com.ilop.sthome.ui.activity.device.DeviceHistoryActivity;
import com.ilop.sthome.ui.activity.device.DeviceSettingActivity;
import com.ilop.sthome.ui.activity.device.GatewayMainActivity;
import com.ilop.sthome.ui.activity.main.MainActivity;
import com.ilop.sthome.ui.dialog.TipDialog;
import com.ilop.sthome.utils.ConfigureUtil;
import com.ilop.sthome.utils.greenDao.utils.DeviceDaoUtil;
import com.ilop.sthome.view.ColorArcProgressBar;
import com.siterwell.familywellplus.R;
import com.siterwell.familywellplus.databinding.ActivityDetailTempControlBinding;

/**
 * @author skygge
 * @date 2019-12-12.
 * GitHub：javofxu@github.com
 * email：skygge@yeah.net
 * description：温控器详情页
 */
public class TempControlDetailActivity extends ContainLoginActivity<ThermostatPresenter, ActivityDetailTempControlBinding> implements ThermostatContract.IView {

    private int setting_mode = -1;
    private int mEntrance = -1;
    private TipDialog mDialog;

    private String mDeviceName;
    private int mDeviceId;
    private DeviceInfoBean mDevice;
    private SetLoadingDialog mLoadingDialog;
    private long lastBackKeyDownTick = 0;
    private static final long MAX_DOUBLE_BACK_DURATION = 10000;

    private boolean mFaMenEnable = false;
    private boolean mClockEnable = false;
    private boolean mWindowEnable = false;

    private boolean mFaMenEnable2 = false;
    private boolean mClockEnable2 = false;
    private boolean mWindowEnable2 = false;

    private int mCurrentMode = -1;
    private float mCurrentPro;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_detail_temp_control;
    }

    @Override
    protected void initialize() {
        super.initialize();
        mDeviceName = getIntent().getStringExtra(CommonId.KEY_DEVICE_NAME);
        mDeviceId = getIntent().getIntExtra(CommonId.KEY_DEVICE_ID,-1);
        mEntrance = getIntent().getIntExtra(CommonId.KEY_DEVICE_TYPE,-1);
        mDevice = DeviceDaoUtil.getInstance().findByDeviceId(mDeviceName, mDeviceId);
    }

    @Override
    protected void initPresent() {
        super.initPresent();
        mPresent = new ThermostatPresenter(mContext);
    }

    @Override
    protected void initData() {
        super.initData();
        mPresent.getDeviceInfo(mDevice);
    }

    @Override
    protected void initDataBus() {
        super.initDataBus();
        LiveDataBus.get().with(CommonId.KEY_EVENT_REFRESH_DEVICE, EventRefreshDevice.class).observe(this, event -> {
            if (event!=null){
                if (mDeviceName.equals(event.getDeviceName()) && mDeviceId == event.getDevice_id()) {
                    Log.i(TAG, "onEventMainThread: subDevice " + event.getDevice_status());
                    mPresent.refreshStatus(event);
                    if (mLoadingDialog!=null && mLoadingDialog.isShowing()){
                        showToast(getString(R.string.success_set));
                        mLoadingDialog.dismiss();
                        saveSuccess();
                    }
                }
            }
        });

        LiveDataBus.get().with(CommonId.KEY_ANSWER_OK, EventAnswerOK.class).observe(this, event -> {
            if (event!=null){
                Log.i(TAG, "initDataBus: answerOK");
                if (event.getData_str1().length() == 9) {
                    int cmd = Integer.parseInt(event.getData_str1().substring(0, 4), 16);
                    if (cmd == SiterCommand.EQUIPMENT_CONTROL) {
                        if (CommonId.KEY_SUCCESS.equals(event.getData_str2())) {
                            mLoadingDialog.setMsg(getString(R.string.success_test));
                        }
                    }
                }
            }
        });
    }

    @Override
    protected void initListener() {
        super.initListener();
        mDBind.tvSaveThermostat.setOnClickListener(v -> {
            long currentTick = System.currentTimeMillis();
            if (currentTick - lastBackKeyDownTick > MAX_DOUBLE_BACK_DURATION) {
                showLoadingDialog();
                getFunctionState();
                lastBackKeyDownTick = currentTick;
            }else {
                showToast(getString(R.string.please_not_operation_so_quickly));
            }
        });
        mDBind.timerMode.setOnClickListener(v -> {
            if(setting_mode==1){
                timing();
            }else {
                setting_mode = 1;
                refreshView();
            }
            showSaveSetting();
        });
        mDBind.handleMode.setOnClickListener(v -> {
            setting_mode = 2;
            refreshView();
            showSaveSetting();
        });
        mDBind.fangdongMode.setOnClickListener(v -> {
            setting_mode = 0;
            refreshView();
            showSaveSetting();
        });
        mDBind.valveCheck.setOnCheckedChangeListener((buttonView, isChecked) -> {
            this.mFaMenEnable2 = isChecked;
            showSaveSetting();
        });
        mDBind.tongsuoBtn.setOnCheckedChangeListener((buttonView, isChecked) -> {
            this.mClockEnable2 = isChecked;
            showSaveSetting();
        });
        mDBind.windowCheck.setOnCheckedChangeListener((buttonView, isChecked) -> {
            this.mWindowEnable2 = isChecked;
            showSaveSetting();
        });
        mDBind.settingTemp.setOnSeekArcChangeListener(new ColorArcProgressBar.OnSeekArcChangeListener() {
            @Override
            public void onProgressChanged(ColorArcProgressBar seekArc, float progress, boolean fromUser) {
                float mProgress = progress + 5.0f;
                if (mProgress != mCurrentPro){
                    mDBind.tvSaveThermostat.setEnabled(true);
                    mDBind.tvSaveThermostat.setTextColor(ContextCompat.getColor(mContext, R.color.main_color));
                }else if (mProgress == mCurrentPro){
                    mDBind.tvSaveThermostat.setEnabled(false);
                    mDBind.tvSaveThermostat.setTextColor(ContextCompat.getColor(mContext, R.color.text_normal));
                }
            }

            @Override
            public void onStartTrackingTouch(ColorArcProgressBar seekArc) {

            }

            @Override
            public void onStopTrackingTouch(ColorArcProgressBar seekArc) {

            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(TextUtils.isEmpty(mDevice.getSubdeviceName())){
            String title = getString(R.string.temp_controler) + mDevice.getDevice_ID();
            mDBind.detailName.setText(title);
        }else{
            mDBind.detailName.setText(mDevice.getSubdeviceName());
        }
        mPresent.analysisStatus(mDevice.getDevice_status());
    }

    private void refreshView() {
        switch (setting_mode){
            case 0:
                showFunctionView(R.mipmap.timing_nor, R.mipmap.manual_nor, R.mipmap.freeze_sel, 15f, 0);
                String fang_temp = SpUtil.getString(mContext, "cold");
                mCurrentPro = TextUtils.isEmpty(fang_temp) ? 5f : Float.parseFloat(fang_temp);
                mDBind.settingTemp.setCurrentValues(mCurrentPro);
                break;
            case 1:
                showFunctionView(R.mipmap.timing_sel, R.mipmap.manual_nor, R.mipmap.freeze_nor, 30f, 1);
                String auto_temp = SpUtil.getString(mContext, "auto");
                mCurrentPro = TextUtils.isEmpty(auto_temp) ? 21f : Float.parseFloat(auto_temp);
                mDBind.settingTemp.setCurrentValues(mCurrentPro);
                break;
            case 2:
                showFunctionView(R.mipmap.timing_nor, R.mipmap.manual_sel, R.mipmap.freeze_nor, 30f, 2);
                String hand_temp = SpUtil.getString(mContext, "hand");
                mCurrentPro = TextUtils.isEmpty(hand_temp) ? 21f : Float.parseFloat(hand_temp);
                mDBind.settingTemp.setCurrentValues(mCurrentPro);
                break;
        }
    }

    /**
     * 显示设备当前状态
     */
    @Override
    public void showStatus(int res, String status){
        mDBind.root.setBackgroundResource(res);
        mDBind.showStatus.setText(status);
    }

    /**
     * 显示电量
     */
    @Override
    public void showQuantity(int res, String quantity){
        mDBind.quantityPosition.setVisibility(View.VISIBLE);
        mDBind.quantityDesc.setVisibility(View.VISIBLE);
        mDBind.quantityPosition.setImageResource(res);
        mDBind.quantityDesc.setText(quantity);
    }

    /**
     * 显示信号
     */
    @Override
    public void showSignal(int res){
        mDBind.signalPosition.setImageResource(res);
    }

    /**
     * 显示开窗器状态
     * @param enable 使能
     * @param status 状态
     */
    @Override
    public void showWindow(int enable, byte status){
        if(enable!=0) {
            mWindowEnable = true;
            mDBind.windowCheck.setChecked(true);
            if (status == 0) {
                mDBind.windowStatus.setImageResource(R.mipmap.window_enable);
            } else {
                mDBind.windowStatus.setImageResource(R.mipmap.window_enable_warning);
            }
        }else {
            mWindowEnable = false;
            mDBind.windowStatus.setImageResource(R.mipmap.window_un_enable);
            mDBind.windowCheck.setChecked(false);
        }
    }

    /**
     * 显示开阀门状态
     * @param enable 使能
     * @param status 状态
     */
    @Override
    public void showValve(int enable, byte status){
        if(enable!=0) {
            mFaMenEnable = true;
            mDBind.valveCheck.setChecked(true);
            if (status == 0) {
                mDBind.valveStatus.setImageResource(R.mipmap.valve_enable);
            } else {
                mDBind.valveStatus.setImageResource(R.mipmap.valve_enable_warning);
            }
        }else{
            mFaMenEnable = false;
            mDBind.valveStatus.setImageResource(R.mipmap.valve_not_enable);
            mDBind.valveCheck.setChecked(false);
        }
    }

    /**
     * 显示铜锁状态
     * @param status 状态
     */
    @Override
    public void showLock(int status){
        if (status != 0) {
            mClockEnable = true;
            mDBind.tongsuoStatus.setImageResource(R.mipmap.lock_enable);
            mDBind.tongsuoBtn.setChecked(true);
        } else {
            mClockEnable = false;
            mDBind.tongsuoStatus.setImageResource(R.mipmap.lock_not_enable);
            mDBind.tongsuoBtn.setChecked(false);
        }
    }

    @Override
    public void showCurrentMode(int mode) {
        this.mCurrentMode = mode;
    }

    /**
     * 显示功能状态
     * @param time 定时
     * @param hand 手动/自动
     * @param freeze 防冻
     * @param number 设置温度
     */
    @Override
    public void showFunctionView(int time, int hand, int freeze, float number, int mode){
        mDBind.timerMode.setImageResource(time);
        mDBind.handleMode.setImageResource(hand);
        mDBind.fangdongMode.setImageResource(freeze);
        mDBind.settingTemp.setMaxValues(number);
        this.setting_mode = mode;
    }

    @Override
    public void showTipDialog(float num) {
        mDBind.showStatus.setText(getString(R.string.install_mode));
        if((mDialog == null || !mDialog.isShowing()) && num <= 30.0f){
            mDialog = new TipDialog(mContext, ()->{});
            mDialog.setMsg(getString(R.string.gs361_install_construction));
            mDialog.show();
        }
    }

    @Override
    public void dismissTip(){
        if(mDialog!=null && mDialog.isShowing()){
            mDialog.dismiss();
        }
    }

    /**
     * 当前温度和设置温度
     * @param num 设置温度
     * @param temp 当前
     */
    @Override
    public void showCurrentTemp(float num, int temp) {
        mCurrentPro = num;
        mDBind.settingTemp.setCurrentValues(num);
        mDBind.settingTemp.setSubCurrentValues(temp);
    }

    /**
     * 温度设定过高显示离线
     */
    @Override
    public void showOffLine(){
        mCurrentPro = 0f;
        mDBind.settingTemp.setCurrentValues(0f);
        mDBind.settingTemp.setSubCurrentValues(0f);
        mDBind.showStatus.setText(getResources().getString(R.string.offline));
        mDBind.root.setBackgroundResource(R.drawable.device_status_off_line);
        mDBind.tvSaveThermostat.setEnabled(false);
        mDBind.tvSaveThermostat.setTextColor(ContextCompat.getColor(mContext, R.color.text_normal));
        mDBind.quantityPosition.setVisibility(View.GONE);
        mDBind.quantityDesc.setVisibility(View.GONE);
        mDBind.signalPosition.setImageResource(ConfigureUtil.choseSPic("00"));
    }

    private void getFunctionState(){
        float da = mDBind.settingTemp.getCurrentValues();
        int set_temp = (int)Math.floor(da);
        int set_temp_decimal = (String.valueOf(da).contains(".5") ? 1 : 0);
        int valve = (mDBind.valveCheck.isChecked() ? 1 : 0);
        int window = (mDBind.windowCheck.isChecked() ? 1 : 0);
        int lock = (mDBind.tongsuoBtn.isChecked() ? 1 : 0);
        String code = mPresent.getSetFrom(set_temp, set_temp_decimal, setting_mode, valve, window, lock);
        mPresent.sendCodeToSetting(code);
    }

    public void manager(View view){
        Intent intent = new Intent(this, DeviceSettingActivity.class);
        Bundle bundle = new Bundle();
        bundle.putInt(CommonId.KEY_DEVICE_ID, mDeviceId);
        bundle.putString(CommonId.KEY_DEVICE_NAME, mDeviceName);
        intent.putExtras(bundle);
        startActivity(intent);
    }

    public void history(View view){
        Intent intent = new Intent(this, DeviceHistoryActivity.class);
        Bundle bundle = new Bundle();
        bundle.putInt(CommonId.KEY_DEVICE_ID, mDeviceId);
        bundle.putString(CommonId.KEY_DEVICE_NAME, mDeviceName);
        intent.putExtras(bundle);
        startActivity(intent);
    }

    public void detail(View view){
        Intent intent = new Intent(this, DeviceDetailActivity.class);
        intent.putExtra(CommonId.KEY_DEVICE_ID, mDeviceId);
        intent.putExtra(CommonId.KEY_DEVICE_NAME, mDeviceName);
        startActivity(intent);
    }

    public void finish(View view){
        if (mEntrance == -1){
            finish();
        }else {
            Intent intent = new Intent();
            if (mEntrance == 0) {
                intent.setClass(mContext, GatewayMainActivity.class);
            }else {
                intent.setClass(mContext, MainActivity.class);
            }
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
            startActivity(intent);
        }
    }

    private void timing(){
        Intent intent = new Intent(mContext, TimingListActivity.class);
        intent.putExtra(CommonId.KEY_DEVICE_ID, mDeviceId);
        intent.putExtra(CommonId.KEY_DEVICE_NAME, mDeviceName);
        intent.putExtra(CommonId.KEY_RECOMMEND_ID, "1C");
        startActivity(intent);
    }

    private void showLoadingDialog(){
        mLoadingDialog = new SetLoadingDialog(mContext);
        mLoadingDialog.setCancelable(false);
        mLoadingDialog.show();
    }

    /**
     * 修改保存按钮
     */
    private void showSaveSetting(){
        Log.i(TAG, "showSaveSetting: " + mCurrentMode + " ---- " + setting_mode);
        if (mFaMenEnable != mFaMenEnable2 || mClockEnable != mClockEnable2 || mWindowEnable != mWindowEnable2 || mCurrentMode != setting_mode){
            mDBind.tvSaveThermostat.setEnabled(true);
            mDBind.tvSaveThermostat.setTextColor(ContextCompat.getColor(mContext, R.color.main_color));
        }else {
            mDBind.tvSaveThermostat.setEnabled(false);
            mDBind.tvSaveThermostat.setTextColor(ContextCompat.getColor(mContext, R.color.text_normal));
        }
    }

    private void saveSuccess(){
        mFaMenEnable2 = false;
        mClockEnable2 = false;
        mWindowEnable2 = false;
        mCurrentMode = -1;
        mDBind.tvSaveThermostat.setEnabled(false);
        mDBind.tvSaveThermostat.setTextColor(ContextCompat.getColor(mContext, R.color.text_normal));
    }
}
